//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}
//时间格式转换为时间戳
function js_strto_time(time) {
    var new_str = time.replace(/:/g, '-');
    new_str = new_str.replace(/ /g, '-');
    new_str = new_str.replace(/\//g, '-');
    var arr = new_str.split("-");
    var datum = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
    return strtotime = datum.getTime() / 1000;
}
//时间戳数据转换为时间格式
function js_date_time(unixtime) {
    var timestr = new Date(parseInt(unixtime)*1000);
    var year= timestr.getFullYear(); 
    var month= timestr.getMonth()+1; 
    var date= timestr.getDate(); 
    var hour= timestr.getHours(); 
    var minute= timestr.getMinutes(); 
    var second= timestr.getSeconds(); 
    var datetime = year+"/"+month+"/"+date+" "+hour+":"+minute+":"+second; 
    return datetime;
}

function showData() {
//    overlayer("open");
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/get.do",
        data: {type: type, messageNo: id, instance: DepotName},
        dataType: "json",
        success: function(souData) {
            //souData = $.parseJSON(souData);
            var policy_desc = souData.Comment;
            $(".policy_desc").val(policy_desc);
            var data = souData.Content;
            $("#C_type").val(data.C_type);
            $("#Adv_URL").val(data.Adv_URL);
            $("#Drop_Protocol").val(data.Drop_Protocol);
            $("#Packet_Drop_Ratio").val(data.Packet_Drop_Ratio);
            var C_TimeSlot_arr = data.C_TimeSlots.C_TimeSlot;
            var timeStr = "";
            for (var i = 0; i < C_TimeSlot_arr.length; i++) {
                var C_Starttime = js_date_time(C_TimeSlot_arr[i].C_Starttime * 1);
                var C_Stoptime = js_date_time(C_TimeSlot_arr[i].C_Stoptime * 1);//C_TimeSlot_arr[i].C_Stoptime;
                timeStr += '<li><span>' + C_Starttime + '-' + C_Stoptime + '</span><button class="btn btn-link" type="button" onclick="delTime(this)"><i class="icon icon-remove red"></i></button></li>';
            }
            $("#list").append(timeStr);

        }
    });


}

//获取表单数据
function generateParameter() {
    var lis = $("ul#list").find("li");
//    var len = lis.length;
    var obj = {};
    obj.C_type = $("#C_type option:selected").val();
    obj.C_TimeSlots = {};
    obj.C_TimeSlots.C_TimeSlot = [];
    obj.Adv_URL = $("#Adv_URL").val();
    obj.Drop_Protocol = $("#Drop_Protocol option:selected").val();
    obj.Packet_Drop_Ratio = $("#Packet_Drop_Ratio").val();
    obj.MessageSerialNo = "0";

//    if (len == 0) {
//        alert("还未添加管理时间！");
//        return;
//    } else {
    $.each(lis, function(index, item) {
        var ali = $(item).children("span").html();
        var ali_arr = ali.split("-");
        console.log(ali);
        var tmp = {};
        tmp.C_Starttime = js_strto_time(ali_arr[0]) + "";
        tmp.C_Stoptime = js_strto_time(ali_arr[1]) + "";
        obj.C_TimeSlots.C_TimeSlot.push(tmp);
    });
//    }
    return obj;
}

//添加数据
function save() {

    var form = $(".form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var lis = $("ul#list").find("li");
    var len = lis.length;
    if (len == 0) {
        alert("还未添加管理时间！");
        return;
    }
    if ($("#Packet_Drop_Ratio").val() > 100) {
        alert("百分比值小于100");
        return;
    }
    var comment = $(".policy_desc").val();
    var policy = JSON.stringify(generateParameter());
//    console.log(policy);
//    return;
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/create.do",
        data: {comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("添加成功！");
                previous();
            } else {
                alert("添加失败!");
            }
        }
    });
}

//编辑数据
function edit() {
    var form = $(".form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var comment = $(".policy_desc").val();
    var policy = JSON.stringify(generateParameter());
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/update.do",
        data: {messageNo: id, comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("编辑成功！");
                previous();
            } else {
                alert("编辑失败!");
            }
        }
    });
}

//返回上一级
function previous() {
    window.location = "../policyList.html?type=" + type + "&id=" + DepotID + "&name=" + base64.encode(DepotName) + "";
}

$(function() {
    //时间插件
    var start = {
        elem: '#C_Starttime',
        format: 'YYYY/MM/DD hh:mm:ss',
        istime: true,
        istoday: false,
        festival: true,
        choose: function(datas) {
            end.min = datas; //开始日选好后，重置结束日的最小日期
            end.start = datas //将结束日的初始值设定为开始日
        }
    };
    var end = {
        elem: '#C_Stoptime',
        format: 'YYYY/MM/DD hh:mm:ss',
        istime: true,
        istoday: false,
        festival: true,
        choose: function(datas) {
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(end);

//    setInterval(function () {
//        parent.$("#page-content").attr("height", $("html").height());
//    }, 500);
});
/*
 * 查看旧版本的策略内容
 */
function show_oldPolicy(array, number) {
    var souData = array[number];
    $(".header").text("当前策略在" + souData.CreateTime + "创建,ID为" + souData.MessageNo + ",版本号为" + souData.MessageSerialNo + ",属于" + souData.Instance + "策略库");

    var policy_desc = souData.Comment;
    $(".policy_desc").val(policy_desc);
    var data = souData.Content;
    $("#C_type").val(data.C_type);
    $("#Adv_URL").val(data.Adv_URL);
    $("#Drop_Protocol").val(data.Drop_Protocol);
    $("#Packet_Drop_Ratio").val(data.Packet_Drop_Ratio);
    var C_TimeSlot_arr = data.C_TimeSlots.C_TimeSlot;
    var timeStr = "";
    for (var i = 0; i < C_TimeSlot_arr.length; i++) {
        var C_Starttime = js_date_time(C_TimeSlot_arr[i].C_Starttime * 1);
        var C_Stoptime = js_date_time(C_TimeSlot_arr[i].C_Stoptime * 1);//C_TimeSlot_arr[i].C_Stoptime;
        timeStr += '<li><span>' + C_Starttime + '-' + C_Stoptime + '</span><button class="btn btn-link" type="button" onclick="delTime(this)"><i class="icon icon-remove red"></i></button></li>';
    }
    $("#list").append(timeStr);
}

/*
 *获取所有版本的策略内容 
 */
function getAllPolicy() {
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/history_policy_info.do",
        data: {type: type, instance: getQueryString("DepotName"), messageNo: id},
        dataType: "json",
        success: function(data) {
            policyArray = data;
            policyAmount = data.length
        }
    });
}
